<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.username" placeholder="Title" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter()" />
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter()">
        查询
      </el-button>
      <el-button class="filter-item" type="danger" style="margin-left: 10px;" icon="el-icon-edit" @click="handleCreate">
        Add
      </el-button>
    </div><br>
    <el-table
      :data="list"
      border
      fit
      highlight-current-row
      size="medium"
    >
      <el-table-column align="center" label="序号" width="95">
        <template slot-scope="scope">
          {{ scope.$index+1 }}
        </template>
      </el-table-column>
      <el-table-column label="用户名">
        <template slot-scope="scope">
          {{ scope.row.username }}
        </template>
      </el-table-column>
      <el-table-column label="性别">
        <template slot-scope="scope">
          <span v-if="scope.row.sex == 0">
            女
          </span>
          <span v-else>
            男
          </span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="330" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleUserRole(row,$index)">
            分配角色
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <br>
    <el-pagination
      :current-page="listQuery.page"
      :page-sizes="[3, 5, 15, 20]"
      :page-size="listQuery.limit"
      layout="total, sizes, prev, pager, next, jumper"
      :total="listQuery.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <el-dialog
      width="300px"
      title="角色分配"
      :visible.sync="dialogRoleVisible"
    >
      <el-table
        ref="multipleTable"
        :data="roleList"
        border
        fit
        highlight-current-row
        size="medium"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
        />
        <el-table-column label="角色名">
          <template slot-scope="scope">
            {{ scope.row.rname }}
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogRoleVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="setUserRole()">
          确认
        </el-button>
      </div>
    </el-dialog>

    <el-dialog top="50px" width="600px" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="user" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="user.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="user.password" show-password="true" />
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="user.nickname" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="user.sex" class="filter-item" placeholder="Please select">
            <el-option v-for="item in sex" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogRoleVisible = false">
          取消
        </el-button>
        <el-button type="primary">
          确认
        </el-button>
      </div>
    </el-dialog>

  </div>

</template>

<script>
import axios from 'axios'
export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      list: null,
      roleList: null,
      listLoading: true,
      dialogFormVisible: false,
      dialogRoleVisible: false,
      multipleSelection: [],
      dialogStatus: '',
      textMap: {
        update: '用户修改',
        create: '用户添加'
      },
      uid: '',
      user: {
        username: '',
        password: '',
        sex: '',
        nickname: ''
      },
      sex: [{ 'id': 1, 'name': '男' }, { 'id': 0, 'name': '女' }],
      rules: {
        username: [
          { required: true, message: '用户名不能为空', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { min: 3, max: 6, message: '长度在 3 到 6 个字符', trigger: 'blur' }
        ],
        sex: [{ required: true, message: '请选择性别', trigger: 'change' }]
      },
      listQuery: {
        page: 1,
        limit: 3,
        total: 0,
        username: ''
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      this.listLoading = true
      axios.post('http://localhost:8080/OAManager_war_exploded/userList', this.listQuery).then(
        res => {
          console.log(res)
          this.list = res.data.list
          this.listQuery.total = res.data.total
        }
      )
      axios.get(`http://localhost:8080/OAManager_war_exploded/getRoleList`).then(
        res => {
          this.roleList = res.data
        }
      )
    },
    resetTemp() {
      this.user = {
        username: '',
        password: '',
        sex: '',
        nickname: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          axios.post('http://localhost:8080/OAManager_war_exploded/addUser', this.user).then(
            res => {
              if (res.data === 1) {
                this.dialogFormVisible = false
                this.fetchData()
                this.$notify({
                  title: '成功',
                  message: '添加成功',
                  type: 'success',
                  duration: 2000
                })
              }
            }
          )
        }
      })
    },
    handleSizeChange(size) {
      this.listQuery.limit = size
      this.fetchData()
    },
    handleCurrentChange(size) {
      this.listQuery.page = size
      this.fetchData()
    },
    handleFilter() {
      this.listQuery.page = 1
      this.fetchData()
    },
    handleUserRole(row) {
      // 分配角色弹框
      this.dialogRoleVisible = true
      this.uid = row.id
      axios.get(`http://localhost:8080/OAManager_war_exploded/getUserRole/` + row.id).then(
        res => {
          // this.roleList = res.data
          this.toggleSelection(res.data)
        }
      )
    },
    toggleSelection(rows) {
      this.$refs.multipleTable.clearSelection()
      // if (rows) {
      rows.forEach(row => {
        this.$refs.multipleTable.toggleRowSelection(
          this.roleList.find(item => {
            return row.rid === item.rid // 注意这里寻找的字段要唯一，示例仅参考
          }), true)
      })
      // } else {
      //   this.$refs.multipleTable.clearSelection()
      // }
    },
    handleSelectionChange(val) {
      // 分配角色复选框选中
      this.multipleSelection = val
    },
    setUserRole() {
      // 分配角色操作
      const rids = []
      this.multipleSelection.forEach(r => {
        rids.push(r.rid)
      })
      if (rids.length > 0) {
        axios.post(`http://localhost:8080/OAManager_war_exploded/grantRole`,
          { 'uid': this.uid, 'rids': rids }
        ).then(res => {
          if (res.data > 0) {
            this.dialogRoleVisible = false
            this.$notify({
              title: '成功',
              message: '分配角色成功',
              type: 'success',
              duration: 2000
            })
          }
        })
      } else {
        this.$message({
          message: '请选择角色',
          type: 'warning'
        })
      }
    }
  }
}
</script>
